package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.PassWordService;
import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/password")
public class PasswordController {
    @Reference
    private PassWordService passWordService;
    @RequestMapping("/updatePassWord")
    public Result updatePassWord(@RequestBody Map map){

            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String age = String.valueOf(map.get("age"));
            String name = String.valueOf(map.get("name"));
            String pass = String.valueOf(map.get("pass"));
            String checkPass = String.valueOf(map.get("checkPass"));
            User user = passWordService.findByUserName(name);
            if(user != null){
                String password = user.getPassword();
                boolean matches = bCryptPasswordEncoder.matches(age, password);
                if(matches){
                   if(pass != null && checkPass != null && pass.equals(checkPass)){
                       Map m = new HashMap();
                       m.put("username",user.getUsername());
                       String encode = bCryptPasswordEncoder.encode(pass);
                       m.put("password",encode);
                       passWordService.updateUser(m);
                       return new Result(true,MessageConstant.UPDATE_PASSWORD_SUCCESS);
                   }
                }
            }
            return new Result(false,MessageConstant.UPDATE_PASSWORD_FAIL);
    }
}
